import {
  Table,
  Button,
  Popconfirm,
  Form,
  InputNumber,
  Select,
  Divider,
  Input,
  DatePicker,
  Checkbox,
} from 'antd';
import React, { Component } from 'react';
import BaseComponent from '@/components/BaseComponent';
import styles from './index.less';
import styled from 'styled-components';
import options from './options';

const { Option } = Select;

const FormItemBox = styled.div`
  display: flex;
  align-items: center;
`;

/**
 * 内镜详情
 */
@Form.create()
class EsophagusView extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      form: [],
      data: [
        {
          id: this.generateId(),
        },
      ],
      columns: [],
      // 报告单存放地址
      reportFilePath: '',
      // 报告单url访问地址
      reportFileUrl: '',
      // 是否正在上传
      isUploading: false,
    };
  }

  componentDidMount() {
    const { sg } = this.props;

    if (sg !== undefined) {
      this.setState({
        data: sg,
      });
    }
    this.getColumns();
  }

  /**
   * 返回用户输入
   * @returns {*}
   */
  getUserInput = () => {
    const { form } = this.props;
    const { data } = this.state;

    const size = data.length;
    const values = form.getFieldsValue();

    const keys = Object.keys(values);

    const result = [];

    for (let i = 0; i < size; i++) {
      let obj = {};
      const ownKeys = keys.filter(each => {
        const tmp = each.split('-');
        const index = tmp[1];
        return index == i;
      });
      ownKeys.forEach(key => {
        const realKey = key.split('-')[0];
        // 'date-picker': fieldsValue['date-picker'].format('YYYY-MM-DD'),
        if (realKey.indexOf('Time')) obj[`${realKey}`] = values[key]
        else obj[`${realKey}`] = values[key];


      });
      result.push(obj);
    }
    console.log('resultresultresultresult', result);
    // this.props.handleChildData(result);
    return result;
  };

  getColumns = () => {
    const { form, disabled = false } = this.props;
    const { getFieldDecorator } = form;
    let cs = [
      {
        title: '随访次数',
        render: (text, record, index) => {
          const { number } = record;
          return (
            <FormItemBox style={{ width: '100px' }}>
              <Form.Item>
                {getFieldDecorator(`number-${index}`, {
                  initialValue: number,
                })(
                  <div>
                    <Input
                      name={`number-${index}`}
                      disabled={disabled}
                      placeholder={'请输入'}
                      style={{ width: '100px', marginRight: '8px' }}
                      onChange={this.saveData()}
                    />
                  </div>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },
      {
        title: '计划随访日期',
        render: (text, record, index) => {
          const { planTime } = record;

          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`planTime-${index}`, {
                  initialValue: planTime,
                })(
                  <div>
                    <DatePicker
                      name={`planTime-${index}`}
                      disabled={disabled}
                      showTime
                      format="YYYY-MM-DD"
                      placeholder={'请选择'}
                      style={{ width: '120px' }}
                      onChange={this.saveData(`planTime-${index}`)}
                    />
                  </div>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },
      {
        title: '实际随访时间',
        render: (text, record, index) => {
          const { actualTime } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`actualTime-${index}`, {
                  initialValue: actualTime,
                })(
                  <div>
                    <DatePicker
                      disabled={disabled}
                      showTime
                      name={`actualTime-${index}`}

                      format="YYYY-MM-DD"
                      placeholder={'请选择'}
                      style={{ width: '120' }}
                      onChange={this.saveData(`actualTime-${index}`)}
                    />
                  </div>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },

      {
        title: '食管最高病例代码',
        render: (text, record, index) => {
          const { esophagus } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`esophagus-${index}`, {
                  initialValue: esophagus,
                })(
                  <Select
                    name={`esophagus-${index}`}

                    disabled={disabled}
                    placeholder="请选择"
                    style={{ width: '150px' }}
                    onSelect={this.saveData(`esophagus-${index}`)}
                  >
                    {options.map(item => (<Option key={item.value} value={item.value}> {item.label}</Option>))}

                  </Select>
                )}
              </Form.Item>
            </FormItemBox >
          );
        },
      },

      {
        title: '贲门最高病理代码',
        render: (text, record, index) => {
          const { cardia } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`cardia-${index}`, {
                  initialValue: cardia,
                })(
                  <Select
                    disabled={disabled}
                    placeholder="请选择"
                    name={`cardia-${index}`}

                    style={{ width: '150px' }}
                    onSelect={this.saveData(`cardia-${index}`)}
                  >
                    {options.map(item => (<Option key={item.value} value={item.value}> {item.label}</Option>))}
                  </Select>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },

      {
        title: '胃最高病理代码',
        render: (text, record, index) => {
          const { stomach } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`stomach-${index}`, {
                  initialValue: stomach,
                })(
                  <Select
                    disabled={disabled}
                    placeholder="请选择"
                    name={`stomach-${index}`}

                    style={{ width: '150px' }}
                    onSelect={this.saveData(`stomach-${index}`)}
                  >
                    {options.map(item => (<Option key={item.value} value={item.value}> {item.label}</Option>))}
                  </Select>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },
      {
        title: '十二指肠最高病理代码',
        render: (text, record, index) => {
          const { duodenum } = record;
          return (
            <FormItemBox>
              <Form.Item>
                {getFieldDecorator(`duodenum-${index}`, {
                  initialValue: duodenum,
                })(
                  <Select
                    name={`duodenum-${index}`}

                    disabled={disabled}
                    placeholder="请选择"
                    style={{ width: '150px' }}
                    onSelect={this.saveData(`duodenum-${index}`)}
                  >
                    {options.map(item => (<Option key={item.value} value={item.value}> {item.label}</Option>))}
                  </Select>
                )}
              </Form.Item>
            </FormItemBox>
          );
        },
      },

      {
        title: '操作',
        width: 160,
        fixed: 'right',
        render: (text, record, index) => {
          return disabled ? null : (
            <div style={{ textAlign: 'left' }}>
              <Button
                style={{ marginRight: '8px' }}
                type="primary"
                size={'small'}
                onClick={() => this.handleAdd()}
              >
                添加
              </Button>
              <Popconfirm
                title="确定执行当前操作吗?"
                onConfirm={() => this.handleDelete(record.id)}
              >
                <Button type="danger" size={'small'}>
                  删除
                </Button>

                {/* <Button type="danger" size={'small'} onChange={this.saveData}>
                  保存
                </Button> */}
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    this.setState({
      columns: cs,
    });
  };

  handleDelete = id => {
    const data = [...this.state.data];
    if (data.length === 1) {
      this.errorMessage('至少保留一行！');
      return;
    }
    this.setState({
      data: data.filter(item => item.id !== id),
    });
  };

  handleAdd = () => {
    const { data } = this.state;
    const newData = {
      id: this.generateId(),
    };
    this.setState({
      data: [...data, newData],
    });
  };

  saveData = target => {
    return (e) => {
      const { form } = this.props;
      if (e.target) {
        const { target } = e
        form.setFieldsValue({ [target.name]: target.value })
      } else {
        if (target.indexOf('Time') >= 0) {
          form.setFieldsValue({ [target]: e.format("YYYY-MM-DD") })
        } else form.setFieldsValue({ [target]: e })
      }

     this.props.handleChildData(this.getUserInput());
    }

    // form.setFieldsValue({ [target.name]: target.value })


    // this.props.handleChildData(this.getUserInput());

  };

  render() {
    const { data, columns } = this.state;
    return (
      <div className={styles.editableTable}>
        <h3>随访情况</h3>
        <Divider />
        <Table
          scroll={{ x: true }}
          rowKey={'id'}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={data}
          columns={columns}
          pagination={false}
        />
      </div>
    );
  }
}

export default EsophagusView;
